<template>
  <section class="pay_content">
    <div class="pay_fee_box">
      <div class="pay_icon_box">
        <i class="iconfont iconqian"></i>
      </div>
      <div class="pay_money_box">
        <label>应收金额：</label>
        <label style="font-size:26px;">￥{{total}}</label>
      </div>
      <div class="pay_menu">
        <ul>
          <li>
            <label>订单号</label>
            <label>{{orderCode}}</label>
          </li>
          <li>
            <label>门诊号</label>
            <label>{{detail.archivesCode}}</label>
          </li>
          <li>
            <label>姓名</label>
            <label>{{detail.name}}</label>
          </li>
          <li>
            <label>就诊日期</label>
            <label>{{detail.lastVisitTime}}</label>
          </li>
          <li v-if="showDetail">
            <label>收费明细</label>
            <label style="cursor:pointer;" @click="getDetail()">点击查看</label>
          </li>
        </ul>
      </div>
    </div>
    <div class="pay_money_content">
      <el-form :model="form" label-width="140px">
        <el-form-item label="减免金额：">
          <el-input
            style="width:200px;"
            @blur="derate()"
            :disabled="showdiscount"
            v-model="form.reductionMoney"
          >
            <template slot="append">元</template>
          </el-input>
          <label style="margin-top:0px;width:initial;">
            （减免折扣
            <el-input v-model="form.discount" class="remission_input"></el-input>%）
          </label>
        </el-form-item>
        <el-form-item label="支付类型">
          <el-checkbox-group class="pay_source_box" @change="changeCheck" v-model="form.source">
            <el-checkbox :disabled="isChecked" :label="1" name="type">医保支付</el-checkbox>
            <el-checkbox :disabled="isChecked" :label="2" name="type">挂账金额</el-checkbox>
            <el-checkbox :disabled="isChecked" :label="3" name="type">商保支付</el-checkbox>
            <el-checkbox :disabled="isChecked" :label="4" name="type">使用卡券</el-checkbox>
            <el-checkbox :disabled="isChecked" :label="6" name="type">余额支付</el-checkbox>
            <el-checkbox :disabled="isChecked" :label="5" name="type">积分</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-for="(item,index) in sourceItem" :key="index" label>
          <el-input @blur="derate(item)" :disabled="isChecked" v-model="item.payMoney">
            <template slot="prepend">{{item.name}}</template>
            <template slot="append">元</template>
          </el-input>
          <label
            v-if="item.source==6"
            style="text-align:right;color:#9B9B9B;"
          >卡内余额：￥ {{detail.patientMoney}}</label>
          <label
            v-if="item.source==5"
            style="text-align:right;color:#9B9B9B;"
          >总积分：{{detail.patientScore}} （单次上限{{jfUse.mostNum}}积分）</label>
        </el-form-item>
        <el-form-item label>
          <div class="pay_switch_box">
            <label
              v-if="residueMoney"
              style="width:initial"
              class="pay_label"
            >还需支付：￥{{residueMoney}}</label>
            <!-- <label class="pay_switch">
              <span style="display:inline-block;margin-right:10px;">组合支付</span>
              <el-switch
                class
                v-model="paySouce"
                @change="changePaySource"
                :active-value="1"
                :inactive-value="2"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </label>-->
          </div>
          <!-- <div v-if="paySouce==1" class="tooltip_box">必须选择两种支付方式（不支持同时选择支付宝和微信）</div> -->
          <div>
            <el-button
              v-for="(item,index) in payType"
              @click="pay(item)"
              :disabled="item.disabled"
              :key="index"
            >{{item.name}}</el-button>
            <!-- <el-button @click="pay(2)">银行卡</el-button>
            <el-button @click="pay(3)">微信支付</el-button>
            <el-button @click="pay(4)">支付宝支付</el-button>-->
          </div>
        </el-form-item>
        <el-form-item v-if="isCash" label="现  金：">
          <el-input @blur="getMoney(1)" v-model="form.xinjin">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="isCard" label="银行卡：">
          <el-input @blur="getMoney(2)" v-model="form.yinhangka">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="isAliPay" label="支付宝：">
          <el-input @blur="getMoney(3)" v-model="form.zhifubao">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="isWpay" label="微  信：">
          <el-input @blur="getMoney(4)" v-model="form.weixin">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="找   零：">{{balanceMoney}}元</el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.note"></el-input>
        </el-form-item>
      </el-form>
      <div class="btn_pay_box">
        <el-button @click="onSubmit()" :loading="btnLoading" class="pay_btn">￥收费</el-button>
      </div>
    </div>
    <pay v-model="editPay" v-if="editPay"></pay>
    <!-- <iframe v-if="showOrder" frameborder="0" height="0px" width="0px" ref="iframe" src="/print/chargerecipe.html"></iframe> -->
  </section>
</template>
<script>
import validate from "@/_js/validate.js";
export default {
  data() {
    return {
      form: {
        payMoney: "",
        type: "",
        xinjin: 0,
        zhifubao: 0,
        weixin: 0,
        yinhangka: 0,
        totalMoney: "", //总金额
        note: "", //备注
        recordNum: "", //总积分数量
        realityMoney: "", //实际金额
        orderId: "", //订单id
        discount: "", //折扣数
        reductionMoney: 0, //减免金额
        source: [] //1医保 2挂账 3商保 4.卡券 5.积分 6.余额 7.现金 8.支付宝 9.微信 10.银行卡 11.找零 12.赠送余额
      },
      showdiscount: false,
      showOrder: false,
      balanceMoney: 0,
      btnLoading: false,
      num: 4,
      isPay: false,
      rules: [
        {
          totalMoney: [
            { required: true, message: "此项必填", trigger: "blur" },
            { validate: validate.vPeopleNumber, trigger: "blur" }
          ]
        }
      ],
      total: 0,
      editPay: false,
      isCash: false,
      isCard: false,
      isAliPay: false,
      isWpay: false,
      paySouce: 2,
      isTwo: false,
      detail: "",
      flog: 0,
      sourceItem: [],
      dispenser: 0,
      orderCode: "",
      payType: [
        {
          disabled: false,
          id: 1,
          name: "现金"
        },
        {
          disabled: false,
          id: 2,
          name: "银行卡"
        },
        {
          disabled: false,
          id: 3,
          name: "支付宝"
        },
        {
          disabled: false,
          id: 4,
          name: "微信"
        }
      ],
      payList: [],
      sourName: {
        1: "医保金额",
        2: "挂账金额",
        3: "商保金额",
        4: "使用卡券",
        5: "使用积分",
        6: "余额支付"
      },
      orderInfo: "",
      orderId: "",
      residueMoney: 0,
      jfUse: "",
      isChecked: false,
      showDetail: false,
      isSource: false
    };
  },
  created() {
    let th = this;
    th.getIntegralRuleById();
    th.orderCode = th.$route.query.orderCode;
    th.orderId = th.$route.query.orderId;
    if (th.$route.query.id) {
      th.showDetail = true;
    }
  },
  mounted() {
    let th = this;
    th.open();
    let source = th.$route.query.source;
    if (source) {
      th.isSource = true;
    }
  },
  methods: {
    //积分
    getIntegralRuleById() {
      let th = this;
      th.$api
        .getIntegralRuleById({ hpId: th.adminUser.hpId, type: 1 })
        .then(res => {
          if (res.executed) {
            th.jfUse = res.integralRuleList[0];
          }
        });
    },
    open() {
      let th = this;
      let total = 0;
      th.verifyUrlAttack(th.$route.query).then(() => {
        // th.total = th.$route.query.total;
        th.residueMoney = th.$route.query.total;
        let uid = th.jieMi(th.$route.query.patientId);
        th.$api
          .getThePatientLibraryById({ patientId: uid, hpId: th.adminUser.hpId })
          .then(res => {
            if (res.executed) {
              th.detail = res.thePatientLibraryDetail;
            }
          });
        th.$api.getOrder({ orderId: th.$route.query.orderId }).then(res => {
          if (res.executed) {
            let list = res.dataBody.list;
            for (let i = 0; i < list.length; i++) {
              total += Number(list[i].realityMoney);
            }
            th.total = total;
          }
        });
      });
    },
    getDetail() {
      let th = this;
      let id = th.$route.query.id;
      if (id) {
        th.$router.push({
          path: "/page/chargeDetail",
          query: th.getUrlToken({
            id: id,
            patientId: th.$route.query.patientId
          })
        });
      }
    },
    pay(item) {
      let th = this;
      //判断是否组合支付
      if (th.paySouce == 2) {
        //非组合支付
        if (item.id == 1) {
          th.isCash = !th.isCash;
          th.isCard = false;
          th.isWpay = false;
          th.isAliPay = false;
        } else if (item.id == 2) {
          th.isCard = !th.isCard;
          th.isCash = false;
          th.isWpay = false;
          th.isAliPay = false;
        } else if (item.id == 3) {
          th.isAliPay = !th.isAliPay;
          th.isCash = false;
          th.isCard = false;
          th.isWpay = false;
        } else {
          th.isWpay = !th.isWpay;
          th.isCash = false;
          th.isCard = false;
          th.isAliPay = false;
        }
      } else {
        //组合支付
        if (item.id == 1) {
          th.isCash = !th.isCash;
        } else if (item.id == 2) {
          th.isCard = !th.isCard;
        } else if (item.id == 3) {
          th.isAliPay = !th.isAliPay;
          // th.payType[3].disabled = th.isAliPay;
        } else {
          th.isWpay = !th.isWpay;
          // th.payType[2].disabled = th.isWpay;
        }
      }
      th.form.xinjin = 0;
      th.form.yinhangka = 0;
      th.form.zhifubao = 0;
      th.form.weixin = 0;
      th.residueMoney = th.total;
      th.balanceMoney = 0;
    },
    changePaySource() {
      let th = this;
      th.isCash = false;
      th.isCard = false;
      th.isWpay = false;
      th.isAliPay = false;
      th.payType[3].disabled = false;
      th.payType[3].disabled = false;
      //=====
    },
    changeCheck(item) {
      let list = [];
      let th = this;
      let _item = th.sourceItem;
      for (let i = 0; i < item.length; i++) {
        let arr = {
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: 0,
          source: "",
          sourceId: "",
          remark: "",
          status: "",
          disabled: false,
          isDeleted: "",
          name: ""
        };
        arr.source = item[i];
        arr.name = th.sourName[item[i]];
        for (let j = 0; j < _item.length; j++) {
          if (_item[j].name == arr.name) {
            arr.payMoney = _item[j].payMoney;
          }
        }
        if (arr.name != "") {
          list.push(arr);
        }
      }
      th.sourceItem = list;
    },
    openPay() {
      let th = this;
      if (th.isWpay || th.isAliPay) {
        th.editPay = true;
      }
    },
    //计算金额
    derate(it) {
      let th = this;
      let money = 0;
      let residueMoney =0;//余额
      if (it != undefined) {
        if (it.source == 5) {
          if (Number(it.payMoney) > Number(th.detail.patientScore)) {
            th.$message.error("积分不足！！");
            it.payMoney = 0;
            return false;
          }
          if (Number(it.payMoney) >= th.jfUse.mostNum) {
            it.payMoney = th.jfUse.mostNum;
            return false;
          } else {
            it.payMoney = parseInt(it.payMoney / th.jfUse.useNum) * th.jfUse.getNum;
          }
        }else if(it.source == 6){
           if (Number(it.payMoney) > Number(th.detail.patientMoney)) {
            th.$message.error("余额不足！！");
            it.payMoney = 0;
            return false;
          }else{
            residueMoney=Number(th.total) - Number(it.payMoney);
          }
        }
        if (it.payMoney > th.total) {
          th.$message.warning("金额填写有误！");
          it.payMoney = 0;
        }
      } else {
        //计算折扣数
        let _discount =  (Number(th.form.reductionMoney) / Number(th.total)) * 100;  th.form.discount = _discount.toFixed(2);
      }
      //减免
      let reductionMoney = th.form.reductionMoney;
      //剩余
      let residueMoney = Number(th.total) - Number(reductionMoney);
      if (reductionMoney != "") {
        // if (Number(reductionMoney) > Number(residueMoney)) {
        //   th.$message.error("减免金额不能大于总金额！");
        //   return false;
        // } else {
        //   residueMoney = Number(th.total) - Number(reductionMoney);
        // }
        if (Number(residueMoney) < 0) {
          th.$message.error("减免金额不能大于总金额！");
          return false;
        } else {
          residueMoney = Number(th.total) - Number(reductionMoney);
        }
      }
      //其他付费
      let item = th.sourceItem;
      //计算其他付费时，还需支付价格
      for (let i = 0; i < item.length; i++) {
        if (item[i].payMoney > residueMoney) {
          th.$message.error(item[i].name + "不能大于总金额！");
          break;
        } else {
          residueMoney = Number(residueMoney) - Number(item[i].payMoney);
        }
      }
      if (residueMoney) {
        th.residueMoney = Number(residueMoney).toFixed(2);
      } else {
        th.residueMoney = th.total;
      }
    },
    getDispenser() {
      let th = this;
      if (Number(th.form.realityMoney) < Number(th.residueMoney)) {
        th.$message.error("请输入正确的金额！");
        return false;
      }
      th.dispenser = Number(th.form.realityMoney - th.residueMoney).toFixed(2);
    },
    onSubmit() {
      let th = this;
      let _item = [];
      let oldMoney = th.residueMoney;
      let isGz = false;
      if (th.sourceItem.length > 0) {
        let list = th.sourceItem;
        for (let i = 0; i < list.length; i++) {
          if (list[i].source == 2) {
            isGz = true;
          }
          let arr = {
            billPayId: "",
            billPayCode: "",
            billId: "",
            payMoney: list[i].payMoney,
            source: list[i].source,
            sourceId: "",
            remark: "",
            status: "",
            isDeleted: ""
          };
          arr = Object.assign(arr, list[i]);
          arr.remark = list[i].note;
          _item.push(arr);
          oldMoney = Number(oldMoney - list[i].payMoney).toFixed(2);
        }
      }
      if (th.isCash == true) {
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.form.xinjin,
          source: 7,
          sourceId: "",
          remark: "",
          status: "",
          isDeleted: ""
        });
        oldMoney = Number(th.form.xinjin - oldMoney).toFixed(2);
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.balanceMoney,
          source: 11,
          sourceId: "",
          remark: "",
          status: "",
          isDeleted: ""
        });
      }
      if (th.isCard == true) {
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.form.yinhangka,
          source: 10,
          sourceId: "",
          remark: "",
          status: "",
          isDeleted: ""
        });
        oldMoney = Number(th.form.yinhangka - oldMoney).toFixed(2);
      }
      if (th.isAliPay == true) {
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.form.zhifubao,
          source: 8,
          sourceId: "",
          remark: "",
          status: "",
          isDeleted: ""
        });
        oldMoney = Number(th.form.zhifubao - oldMoney).toFixed(2);
      }
      if (th.isWpay == true) {
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.form.weixin,
          source: 9,
          sourceId: "",
          remark: "",
          status: "",
          isDeleted: ""
        });
        oldMoney = Number(th.form.weixin - oldMoney).toFixed(2);
      }
      //判断是否需要找零
      if(th.balanceMoney)
      let j = {
        orderId: th.orderId,
        reductionMoney: th.form.reductionMoney,
        note: th.form.note,
        billPaywaysJson: JSON.stringify(_item)
      };
      if (th.form.reductionMoney != null) {
        j.reductionMoney = th.form.reductionMoney;
        j.note = th.form.note;
      } else {
        j.reductionMoney = 0;
      }
      if (isGz == false) {
        if (Number(oldMoney) < 0) {
          th.$message.error("支付金额不足！");
          return false;
        }
      }
      th.btnLoading = true;
      // th.showLoading();
      th.$api
        .payOrder(j)
        .then(res => {
          if (res.executed) {
            th.$message.success("支付成功");
            // th.showLoading(false);
            th.$router.push({ path: "/page/chargeIndex" });
            // th.showOrder = true;
            th.btnLoading = false;
          } else {
            th.$message.error(res.message);
            th.btnLoading = false;
          }
        })
        .catch(error => {
          th.$message.error(res.message);
          th.btnLoading = false;
        });
    },
    getMoney(type) {
      let th = this;
      let _balanceMoney = 0;
      let _residueMoney = 0;
      if (th.paySouce == 2) {
        if (type == 1) {
          if (th.form.xinjin) {
            _balanceMoney =
              Number(th.form.xinjin) - Number(th.getDinnerMoney());
            _residueMoney = Number(th.getDinnerMoney());
          }
        } else if (type == 2) {
          if (th.form.yinhangka) {
            _balanceMoney =
              Number(th.form.yinhangka) - Number(th.getDinnerMoney());
            _residueMoney = Number(th.getDinnerMoney());
          }
        } else if (type == 3) {
          if (th.form.zhifubao) {
            _balanceMoney =
              Number(th.form.zhifubao) - Number(th.getDinnerMoney());
            _residueMoney = Number(th.getDinnerMoney());
          }
        } else if (type == 4) {
          if (th.form.weixin) {
            _balanceMoney =
              Number(th.form.weixin) - Number(th.getDinnerMoney());
            _residueMoney = Number(th.getDinnerMoney());
          }
        }
      } else {
        let allMoney =
          Number(th.form.xinjin) +
          Number(th.form.zhifubao) +
          Number(th.form.weixin) +
          Number(th.form.yinhangka);
        _balanceMoney = Number(allMoney) - Number(th.getDinnerMoney());
        _residueMoney = Number(th.getDinnerMoney());
      }

      if (Number(_residueMoney) < 1) {
        _residueMoney = 0;
        th.residueMoney = _residueMoney.toFixed(2);
      } else {
        if (_balanceMoney > _residueMoney) {
          th.residueMoney = 0;
        } else {
          th.residueMoney = _residueMoney.toFixed(2);
        }
      }
      th.balanceMoney = _balanceMoney.toFixed(2);
      th.isChecked = true;
      th.showdiscount = true;
    },
    //获取余额
    getDinnerMoney() {
      let th = this;
      let item = th.sourceItem;
      let _toatlMoney = Number(th.total);
      let _residueMoney = Number(th.form.reductionMoney);
      if (_residueMoney != "") {
        _toatlMoney = _toatlMoney - _residueMoney;
      }
      if (item.length > 0) {
        for (let i = 0; i < item.length; i++) {
          _toatlMoney = _toatlMoney - Number(item[i].payMoney);
        }
      }
      return _toatlMoney;
    }
  },
  components: {
    pay: () => import("./_child/otherPay")
  }
};
</script>
<style lang="scss" scoped>
@import "./_css/pay.scss";
</style>